# -*- coding: utf-8 -*-

from core.serializers import CustomModelSerializer
from core.relations import BaseNameWritableRelatedField, UserNameWritableRelatedField
from rest_framework import serializers, status
from .models import Version


class ListVersionSerializer(CustomModelSerializer):
    """
    产品版本-列表序列化器
    """

    product_name = serializers.CharField(read_only=True, source="product.name")
    bugs_count = serializers.SerializerMethodField()

    def get_bugs_count(self, instance):
        return len(instance.bug_set.all())

    class Meta:
        model = Version
        fields = "__all__"
        read_only_fields = ["id"]


class VersionSerializer(CustomModelSerializer):
    """
    产品版本-查询、新增、修改序列化器
    """

    product = BaseNameWritableRelatedField()
    parent = BaseNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )
    owner = UserNameWritableRelatedField(
        required=False, allow_empty=True, allow_null=True
    )

    class Meta:
        model = Version
        fields = "__all__"
        read_only_fields = ["id"]


class VersionTreeSelectSerializer(CustomModelSerializer):
    """
    产品版本-树型菜单序列化器
    """

    class Meta:
        model = Version
        fields = ["id", "name", "parent"]
        read_only_fields = ["id"]
